import React, { useRef, useState } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { addItem, removeItem } from '../store/home';

const Page = () => {
  const [input, setInput] = useState('');
  const ref = useRef(null);
  const list = useSelector((state) => state.home.list);
  const dispatch = useDispatch();

  const handleInput = (e) => {
    setInput(e.target.value);
  };

  const handleSubmit = () => {
    if (!input) {
      alert('输入不得为空！');
      return;
    }
    dispatch(addItem(input));
    setInput('');
    ref.current.value = '';
  };

  const handleDel = (value) => {
    dispatch(removeItem(value));
  };

  return (
    <div>
      <h2>TODO List</h2>

      <input onInput={handleInput} ref={ref} placeholder="请输入" />
      <button onClick={handleSubmit}>确定</button>

      <ul>
        {list.map((item) => {
          return (
            <li key={item}>
              <span style={{ marginRight: '10px' }}>{item}</span>
              <button onClick={() => handleDel(item)}>删除</button>
            </li>
          );
        })}
      </ul>
    </div>
  );
};

const request = () => {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve('做家务')
    }, 1000)
  })
}

Page.initProps = async (store) => {
  const work = await request()
  return store.dispatch(addItem(work));
};

export default Page;
